#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "../core/config.h"
#include "../bus/xbar.h"

static uint8_t mem[RAM_SIZE];
static xbar_slave_intf_t ram_intf;

static uint32_t ram_read(uint32_t addr)
{
    uint32_t data;

    addr = addr & 0x00ffffff;

    data = (mem[addr + 0] << 0) |
            (mem[addr + 1] << 8) |
            (mem[addr + 2] << 16) |
            (mem[addr + 3] << 24);

    return data;
}

static uint32_t ram_write(uint32_t addr, uint8_t be, uint32_t val)
{
    addr = addr & 0x00ffffff;

    if (be & 0x1)
        mem[addr + 0] = (val >> 0) & 0xff;
    if (be & 0x2)
        mem[addr + 1] = (val >> 8) & 0xff;
    if (be & 0x4)
        mem[addr + 2] = (val >> 16) & 0xff;
    if (be & 0x8)
        mem[addr + 3] = (val >> 24) & 0xff;

    return 0;
}

int ram_init()
{
    ram_intf.start_addr = RAM_START_ADDR;
    ram_intf.size = RAM_SIZE;
    ram_intf.read = ram_read;
    ram_intf.write = ram_write;

    xbar_slave_register(&ram_intf);
    return 0;
}
